package com.jyh.blog.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jyh.blog.dao.UniqueViewDao;
import com.jyh.blog.dto.UniqueViewDTO;
import com.jyh.blog.entity.UniqueView;
import com.jyh.blog.service.RedisService;
import com.jyh.blog.service.UniqueViewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import static com.jyh.blog.constant.RedisPrefixConst.UNIQUE_VISITOR;
import static com.jyh.blog.constant.RedisPrefixConst.VISITOR_AREA;
import static com.jyh.blog.enums.ZoneEnum.SHANGHAI;

/**
 * (UniqueView)表服务实现类
 *
 * @author jyh
 * @since 2023-02-19 15:19:20
 */
@Service("uniqueViewService")
public class UniqueViewServiceImpl extends ServiceImpl<UniqueViewDao, UniqueView> implements UniqueViewService {
    @Autowired
    private UniqueViewDao uniqueViewDao;
    @Autowired
    private RedisService redisService;
    //一周访问量
    @Override
    public List<UniqueViewDTO> statisticUniqueViewList() {
        DateTime startTime = DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -7));
        DateTime endTime = DateUtil.endOfDay(new Date());
        return uniqueViewDao.listUniqueViews(startTime, endTime);
    }

    /**
     * 每日访问量
     * 每天 00:00 执行
     */
    @Scheduled(cron = "0 0 0 * * ?",zone = "Asia/Shanghai")
    public void saveUniqueView(){
        //访问用户集合大小即为访问量
        Long count = redisService.sSize(UNIQUE_VISITOR);
        //时间过了十二点，插入数据库为昨天
        UniqueView uniqueView=UniqueView.builder()
                .createTime(LocalDateTimeUtil.offset(LocalDateTime.now(ZoneId.of(SHANGHAI.getZone())),-1, ChronoUnit.DAYS))
                .viewsCount(Optional.of(count.intValue()).orElse(0))
                .build();
        uniqueViewDao.insert(uniqueView);
    }

    /**
     * 清空
     * 每日 00:01 执行
     */
    @Scheduled(cron = "0 1 0 * * ?", zone="Asia/Shanghai")
    public void clearUniqueView(){
        //清空昨天访问量
        redisService.del(UNIQUE_VISITOR);
        //清空昨天访问地区
        redisService.del(VISITOR_AREA);
    }
}

